import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { LoadingOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Layout, Tree, Divider, Spin, Row, Col, Button, InputNumber, Select } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import DictCode from '../../components/DictCode';
import HOCSelect from '@/components/AntDesign/Select';

const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const FormItem = Form.Item;
const { Option } = Select;

@connect(({ busiparamset, loading }) => ({
  busiparamset,
  loading: loading.effects['busiparamset/fetchComList'],
  matLoading: loading.effects['busiparamset/fetchMatList'],
}))
@Form.create()
class List extends PureComponent {
  state = {
    autoExpandParent: true,
    contloading: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    // 获取字典值
    dispatch({
      type: 'busiparamset/fetchDictList',
      payload: ['YES_NO_FLAG'],
    });
    this.orgList();
    this.onSearchMat();
  }

  // 左侧菜单
  orgList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'busiparamset/fetchCorpList',
      payload: {},
    });
  };

  onExpand = () => {
    this.setState({
      autoExpandParent: false,
    });
  };

  // 获取树形数据
  getTreeData = (isLeaf, params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'busiparamset/fetchAreaList',
      payload: { params, isLeaf },
    });
  };

  onLoadData = treeNode => {
    const { dispatch } = this.props;
    const corpId = treeNode.props.dataRef.key;
    dispatch({
      type: 'busiparamset/fetchChildList',
      payload: { corpId },
    });
    return new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, 500);
    });
  };

  onSelect = (selectedKeys, info) => {
    const { form } = this.props;
    if (selectedKeys.length === 0) {
      return;
    }
    const { dispatch } = this.props;
    form.resetFields();
    const { dataRef } = info.node.props;
    const corpId = dataRef.dataInfo ? dataRef.dataInfo.corpId : dataRef.key;
    const corpName = dataRef.dataInfo ? dataRef.dataInfo.parentOrgName : dataRef.corpName;

    dispatch({
      type: 'busiparamset/updateModalData',
      payload: {
        selectedTreeKeys: selectedKeys,
        comFlag: Boolean(info.node.props.dataRef.corpName),
        corpId,
        corpName,
      },
    });
    dispatch({
      type: 'busiparamset/fetchBusiParam',
      payload: { execCorpId: selectedKeys[0] },
    });
  };

  onSearchMat = () => {
    const parameter = {
      relSer: 1,
      // matName: value,
      inpTypeList: [1, 4, 11, 2],
    };
    const { dispatch } = this.props;
    dispatch({
      type: 'busiparamset/fetchMatList',
      payload: parameter,
    });
  };

  // 提交并更新
  save = e => {
    e.preventDefault();
    const {
      form: { validateFieldsAndScroll },
      dispatch,
      busiparamset: { pageInfo, corpId, selectedTreeKeys, corpName },
    } = this.props;
    const { vno, paramId } = pageInfo;
    const inParam = { corpId, execCorpId: selectedTreeKeys[0], corpName, vno, paramId };
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        const obj = {};
        Object.keys(values).forEach(item => {
          if (item === 'billGenRule') {
            obj[item] = Number(values[item]);
          } else if (item === 'template') {
            obj[item] = values[item] && values[item].join(',');
          } else {
            obj[item] = values[item];
          }
        });
        obj.autoDispch = values.autoDispch || '1';
        obj.autoRcvr = values.autoRcvr || '1';
        dispatch({
          type: 'busiparamset/saveParam',
          payload: { ...inParam, ...obj },
        });
      }
    });
  };

  render() {
    const { autoExpandParent, contloading } = this.state;
    const hei = window.screen.height;
    const {
      busiparamset,
      loading,
      form: { getFieldDecorator },
      busiparamset: { bigResult },
      matLoading,
    } = this.props;
    const { treeData, selectedTreeKeys, comFlag, pageInfo } = busiparamset;
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };

    const renderTree = data =>
      data.map(item => {
        if (item.children) {
          return (
            <TreeNode title={item.title} key={item.key} dataRef={item}>
              {renderTree(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode {...item} dataRef={item} />;
      });

    return (
      <PageHeaderWrapper>
        <div>
          <Layout>
            <div className={styles.setSider}>
              <Sider style={{ background: '#fff', width: 274, height: hei }}>
                <div className={styles.setTree} style={{ height: hei }}>
                  {loading ? (
                    <div style={{ textAlign: 'center' }}>
                      <LoadingOutlined /> 加载中
                    </div>
                  ) : (
                    <Tree
                      showLine
                      onSelect={this.onSelect}
                      loadData={this.onLoadData}
                      selectedKeys={selectedTreeKeys}
                      autoExpandParent={autoExpandParent}
                    >
                      {renderTree(treeData)}
                    </Tree>
                  )}
                </div>
              </Sider>
            </div>
            <div className={styles.contentBody}>
              <Content className={styles.controlWrapper}>
                <h3 style={{ margin: '0', fontSize: 14, fontWeight: 'bolder' }}>
                  客服账单参数设置
                </h3>
                <Divider style={{ margin: '13px 0 12px' }} />
                <Form layout="vertical">
                  <Spin spinning={contloading}>
                    <Row gutter={48} className={styles.csBillSetting}>
                      <Col span={12}>
                        <FormItem
                          label={
                            <span style={{ display: 'flex', justifyContent: 'space-between' }}>
                              客服账单生成截止日
                              <span style={{ color: 'rgba(0,0,0,.45)' }}>
                                (默认：当天00:00生效)
                              </span>
                            </span>
                          }
                        >
                          {getFieldDecorator('csBillGenDate', {
                            rules: [{ required: true, message: '请输入' }],
                            initialValue: pageInfo.csBillGenDate,
                          })(<InputNumber min={1} max={31} style={{ width: '100%' }} />)}
                        </FormItem>
                      </Col>
                      <Col span={12} style={{ position: 'relative' }}>
                        <FormItem
                          label={
                            <span style={{ display: 'flex', justifyContent: 'space-between' }}>
                              账单发送财务截止日
                              <span style={{ color: 'rgba(0,0,0,.45)' }}>
                                (默认：当天00:00生效)
                              </span>
                            </span>
                          }
                        >
                          {getFieldDecorator('billDispchFmDate', {
                            rules: [{ required: true, message: '请输入' }],
                            initialValue: pageInfo.billDispchFmDate,
                          })(<InputNumber min={1} max={31} style={{ width: '100%' }} />)}
                        </FormItem>
                      </Col>
                    </Row>
                    <Row gutter={48}>
                      <Col span={12}>
                        <FormItem label="设置账单调差金额上限">
                          {getFieldDecorator('billAdjAmoUprLmt', {
                            rules: [{ required: true, message: '请输入' }],
                            initialValue: pageInfo.billAdjAmoUprLmt,
                          })(
                            <InputNumber
                              min={1}
                              max={9999}
                              precision={0}
                              style={{ width: '100%' }}
                            />
                          )}
                        </FormItem>
                      </Col>
                      <Col span={12}>
                        <FormItem label="客服账单生成规则">
                          {getFieldDecorator('billGenRule', {
                            rules: [{ required: true, message: '请选择' }],
                            initialValue: pageInfo.billGenRule,
                          })(
                            <DictCode
                              allowClear
                              showSearch
                              filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >=
                                0
                              }
                              dictType="BILL_GEN_RULE"
                            />
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                    <Row style={{ padding: '24px 0', lineHeight: 1.5, fontSize: 14 }}>
                      <div style={{ paddingBottom: 5, color: '#787878' }}>注：</div>
                      <Col>
                        <span style={{ color: '#787878' }}>
                          客服账单生成规则：
                          生成业务年月是次月及以前：需要在当月账单中生成业务年月是次月及之前的数据时，例如账单年月是4月份账单，明细中包含业务年月5月及以前的补缴数据，适用于当月申报下月的业务场景；生成业务年月是当月及以前：需要在当月账单中生成业务年月是当月及之前的数据时，
                          例如账单年月是4月份账单，明细中包含业务年月4月及以前的补缴数据，适用于当月申报当月的业务场景；在客户服务系统中客户账单和供应商收费账单生成时生效。
                        </span>
                      </Col>
                    </Row>
                  </Spin>
                </Form>
                {comFlag ? (
                  <div className={styles.tableListForm}>
                    <h3 style={{ margin: '0', fontSize: 14, fontWeight: 'bolder' }}>
                      供应商交互系统自动接发单设置
                    </h3>
                    <Divider style={{ margin: '13px 0 12px' }} />
                    <Form layout="inline">
                      <Spin spinning={contloading}>
                        <Row>
                          <Col span={12}>
                            <FormItem label="自动增员发单" {...formItemLayout}>
                              {getFieldDecorator('autoDispch', {
                                rules: [{ required: true, message: '请输入' }],
                                initialValue: pageInfo.autoDispch,
                              })(<DictCode dictType="YES_NO_FLAG" inputType="3" />)}
                            </FormItem>
                          </Col>
                        </Row>
                        <Row>
                          <Col span={12}>
                            <FormItem label="自动接单" {...formItemLayout}>
                              {getFieldDecorator('autoRcvr', {
                                rules: [{ required: true, message: '请输入' }],
                                initialValue: pageInfo.autoRcvr,
                              })(<DictCode dictType="YES_NO_FLAG" inputType="3" />)}
                            </FormItem>
                          </Col>
                        </Row>
                        <Row style={{ padding: '24px 0', lineHeight: 1.5, fontSize: 14 }}>
                          <div style={{ paddingBottom: 5, color: '#787878' }}>注：</div>
                          <Col>
                            <span style={{ color: '#787878' }}>
                              1. 自动发单：
                              设置自动增员发单后：客户首次关联同一协议时，需要人为做发单操作；客户已经关联协议，并且此协议下再次有发单任务，则系统自动发单；关联的协议中执行地以及报价发生变化后，客户与协议的关联关系也会自动取消；
                            </span>
                          </Col>
                          <Col>
                            <span style={{ color: '#787878' }}>
                              2. 自动接单：
                              设置自动接单后：①增员接单规则：客户首次关联同一协议时，需要人为做接单操作；客户已经关联协议，并且此协议下再次有接单任务，则系统自动接单；②
                              减员接单规则：系统直接自动接单；③调整接单规则：任务类型是社保申报信息和公积金申报信息系统直接自动接单，任务类型是更换协议的需要人员操作接单；
                            </span>
                          </Col>
                        </Row>
                      </Spin>
                    </Form>
                  </div>
                ) : null}
                <div className={styles.tableListForm}>
                  <h3 style={{ margin: '0', fontSize: 14, fontWeight: 'bolder' }}>
                    客服增员可补缴月数限制规则
                  </h3>
                  <Divider style={{ margin: '13px 0 12px' }} />
                  <Form layout="inline">
                    <Spin spinning={contloading}>
                      <Row>
                        <Col span={12}>
                          <FormItem label="本公司执行" {...formItemLayout}>
                            {getFieldDecorator('locLmtFlag', {
                              rules: [{ required: true, message: '请输入' }],
                              initialValue: pageInfo.locLmtFlag && pageInfo.locLmtFlag.toString(),
                            })(<DictCode dictType="LMT_TYPE" inputType="3" />)}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row>
                        <Col span={12}>
                          <FormItem label="供应商执行" {...formItemLayout}>
                            {getFieldDecorator('suppLmtFlag', {
                              rules: [{ required: true, message: '请输入' }],
                              initialValue: pageInfo.suppLmtFlag && pageInfo.suppLmtFlag.toString(),
                            })(<DictCode dictType="LMT_TYPE" inputType="3" />)}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row style={{ padding: '24px 0', lineHeight: 1.5, fontSize: 14 }}>
                        <div style={{ paddingBottom: 5, color: '#787878' }}>注：</div>
                        <Col>
                          <span style={{ color: '#787878' }}>
                            选择限制时：在增员时会根据社保公积金政策中可补缴月数判断，如果业务开始日期超过可补缴月数系统不允许增员，需要调整业务开始日期；
                          </span>
                        </Col>
                        <Col>
                          <span style={{ color: '#787878' }}>
                            选择不限制时：在增员时，系统不会限制可补缴月数
                          </span>
                        </Col>
                      </Row>
                    </Spin>
                  </Form>
                </div>

                <div className={styles.tableListForm}>
                  <h3 style={{ margin: '0', fontSize: 14, fontWeight: 'bolder' }}>
                    客服增员模板设置
                  </h3>
                  <Divider style={{ margin: '13px 0 12px' }} />
                  <Form layout="inline">
                    <Row>
                      <Col span={12}>
                        <FormItem label="模板中包含内容" {...formItemLayout}>
                          {getFieldDecorator('template', {
                            rules: [{ required: false, message: '请输入' }],
                            initialValue: pageInfo.template || undefined,
                          })(
                            <HOCSelect
                              style={{ width: '100%' }}
                              mode="multiple"
                              placeholder="请搜索"
                              // onSearch={this.onSearchMat}
                              filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                              }
                              showSearch
                              notFoundContent={matLoading ? <Spin size="small" /> : '暂无数据'}
                            >
                              {bigResult.map(value => (
                                <Option key={value.matId}>{value.matName}</Option>
                              ))}
                            </HOCSelect>
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                  </Form>
                </div>
                <div className={styles.tableListForm}>
                  <h3 style={{ margin: '0', fontSize: 14, fontWeight: 'bolder' }}>
                    到期提醒天数设置
                  </h3>
                  <Divider style={{ margin: '13px 0 12px' }} />
                  <Form layout="inline">
                    <Spin spinning={contloading}>
                      <Row gutter={48} className={styles.csBillSetting}>
                        <Col span={12}>
                          <FormItem label="商务合同续签提醒天数">
                            {getFieldDecorator('contWarnDate', {
                              rules: [{ required: true, message: '请输入' }],
                              initialValue: pageInfo.contWarnDate,
                            })(
                              <InputNumber
                                min={0}
                                max={100}
                                precision={0}
                                style={{ width: '100%' }}
                              />
                            )}
                          </FormItem>
                        </Col>
                        <Col span={12}>
                          <FormItem label="劳动合同续签提醒天数">
                            {getFieldDecorator('laborContWarnDate', {
                              rules: [{ required: true, message: '请输入' }],
                              initialValue: pageInfo.laborContWarnDate,
                            })(
                              <InputNumber
                                min={0}
                                max={100}
                                precision={0}
                                style={{ width: '100%' }}
                              />
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                    </Spin>
                  </Form>
                </div>
                <Row style={{ textAlign: 'center', marginBottom: '30px' }}>
                  <Authorized authority="mgr:busiParamMGR:saveBusiParam" noMatch={null}>
                    <Button type="primary" onClick={this.save}>
                      提交并更新
                    </Button>
                  </Authorized>
                </Row>
              </Content>
            </div>
          </Layout>
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default List;
